﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain;
using Casamiel.Domain.Request;
using MediatR;
using Newtonsoft.Json;

namespace Casamiel.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public class UpdateCakeStockCommandHandler : IRequestHandler<UpdateCakeStockCommand, bool>
	{
		private readonly INetICService _netICService;
		private readonly IGoodBaseRepository _goodBaseRepository;
		private readonly IMbrStoreRepository _mbrStoreRepository;
		public UpdateCakeStockCommandHandler(INetICService netICService, IGoodBaseRepository goodBaseRepository, IMbrStoreRepository mbrStoreRepository)
		{
			_netICService = netICService;
			_goodBaseRepository = goodBaseRepository;
			_mbrStoreRepository = mbrStoreRepository;
		}

		public async Task<bool> Handle(UpdateCakeStockCommand request, CancellationToken cancellationToken)
		{
			for (int i = 0; i < 200; i++) {
				var storeInfo = await _mbrStoreRepository.GetByStoreIdAsync<ICasaMielSession>(i).ConfigureAwait(false);
				if (storeInfo == null) {
					continue; }

				var data = await _goodBaseRepository.GetProductSkuList<ICasaMielSession>(storeInfo.StoreId).ConfigureAwait(false);

				var stockreq = new ProductStockQueryReq { shopid = storeInfo.RelationId, product = new List<ProductStockReq>() };


				foreach (var item in data) {
					Console.WriteLine($"{item.relationid}=={item.id}");
					stockreq.product.Add(new ProductStockReq {
						pid = $"{item.relationid}",
						count = 1
					});
				}
				var zmodel = await _netICService.Productstockquery(stockreq).ConfigureAwait(false);
				Console.WriteLine($"{JsonConvert.SerializeObject(zmodel)}");
				if (zmodel != null && zmodel.product.Count > 0) {
					List<StoreGoodsStock> list = new List<StoreGoodsStock>();
					// int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(data.relationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30")));
					foreach (var item in data) {
						var info = zmodel.product.FirstOrDefault(c => c.pid == $"{item.relationid}");
						if (info != null) {
							list.Add(new StoreGoodsStock { Id = item.id, Stockquentity = info.count });
						} else {
							list.Add(new StoreGoodsStock { Id = item.id, Stockquentity = 0 });
						}
					}
					Console.WriteLine($"{JsonConvert.SerializeObject(list)}");
					await _goodBaseRepository.UpdateStockquentityAsync<ICasaMielSession>(list).ConfigureAwait(false);
				}

			}
			return true;
		}
	}
}
